<template>
  <!-- 达人切片管理 -->
  <div class="p-2">
    <!-- 头部搜索 -->
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="mb-[10px]" v-show="showSearch">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="状态" prop="enable">
              <el-select v-model="queryParams.enable" placeholder="请选择" clearable style="width: 90px">
                <el-option label="上架" :value="1" />
                <el-option label="下架" :value="0" />
              </el-select>
            </el-form-item>
            <el-form-item v-hasPermi="['gms:section:query']">
              <el-button type="primary" icon="Search" @click="handleQuery()">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery()">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="hover">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['gms:section:add']">新增</el-button>
          </el-col>
          <!-- :columns="columns" -->
          <right-toolbar v-model:showSearch="showSearch" :search="true" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>
      <el-table :data="ordersListl" v-loading="loading" max-height="550" border>
        <el-table-column label="ID" align="center" prop="id" width="180" />
        <el-table-column label="达人昵称" align="center" prop="nickname" />
        <el-table-column label="达人头像" align="center" prop="avatar" min-width="120">
          <template #default="scope">
            <el-image style="width: 80px; height: 80px"
              :src="scope.row.avatar "
              :preview-src-list="[scope.row.avatar]" fit="contain" :preview-teleported="true">
              <template #error>
                <div></div>
              </template>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column label="分成比例" align="center" prop="rate" />
        <el-table-column label="近30日GMV" align="center" prop="orderAmount" width="120" />
        <el-table-column label="直播场次" align="center" prop="liveCount" />
        <el-table-column label="商品总数" align="center" prop="goodsNum" />
        <!-- <el-table-column label="类目简介" align="center" prop="intro" />
        <el-table-column label="切片要求" align="center" prop="demand" /> -->
        <el-table-column label="切片须知" align="center" prop="guide" width="250" :show-overflow-tooltip="true" />
        <el-table-column label="申请人数" align="center" prop="applyNum" />
        <el-table-column label="处理中人数" align="center" prop="handleNum" width="120" />
        <el-table-column label="已处理人数" align="center" prop="successNum" width="120" />
        <el-table-column label="已拒绝人数" align="center" prop="rejectNum" width="120" />
        <el-table-column label="状态" align="center" fixed="right" prop="enable">
          <template #default="scope">
            <el-switch v-model="scope.row.enable" :active-value="1" :inactive-value="0" @change="approve(scope.row)"
              :disabled="enableFlag"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" fixed="right" prop="createTime" width="160" />

        <el-table-column label="操作" align="center" fixed="right" width="100" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="详情" placement="top">
              <el-button link type="primary" icon="View" @click="handleDetails(scope.row)" v-hasPermi="['gms:sectionApply:list']"></el-button>
            </el-tooltip>
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" :disabled="scope.row.enable !== 0"
                @click="handleUpdate(scope.row)" v-hasPermi="['gms:section:edit']">
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" @pagination="getList" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" />
    </el-card>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="suinoeu.title" v-model="suinoeu.visible" width="550px" append-to-body>
      <el-form ref="configFormRef" :model="form" :rules="rules" label-width="100px" style="max-height: 450px;">
        <el-form-item label="达人头像" prop="avatar">
          <el-upload class="avatar-uploader" :action="huonseom.url" :headers="huonseom.headers" :show-file-list="false"
            :on-success="handleAvatarSuccess">
            <img v-if="form.avatar" :src="form.avatar" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="达人昵称" prop="nickname">
          <el-input v-model.trim="form.nickname" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="分成比例" prop="rate">
          <el-input v-model.trim="form.rate" type="number" placeholder="请输入分成比例">
            <template #append>%</template>
          </el-input>
        </el-form-item>
        <el-form-item label="近30日GMV" prop="orderAmount">
          <el-input v-model.trim="form.orderAmount" placeholder="请输入近30日GMV" />
        </el-form-item>
        <el-form-item label="直播场次" prop="liveCount">
          <el-input v-model.trim="form.liveCount" type="number" placeholder="请输入直播场次" />
        </el-form-item>
        <el-form-item label="商品总数" prop="goodsNum">
          <el-input v-model.trim="form.goodsNum" type="number" placeholder="请输入商品总数" />
        </el-form-item>
        <el-form-item label="类目简介" prop="intro">
          <el-input v-model.trim="form.intro" type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" placeholder="请输入类目简介" />
        </el-form-item>
        <el-form-item label="切片要求" prop="demand">
          <el-input v-model.trim="form.demand" type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" placeholder="请输入切片要求" />
        </el-form-item>
        <el-form-item label="切片须知" prop="guide">
          <el-input v-model.trim="form.guide" type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" placeholder="请输入切片须知" />
        </el-form-item>
        
        <!-- <el-form-item label="状态" prop="enable">
          <el-radio-group v-model="form.enable">
            <el-radio v-for="dict in options" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm()">确 定</el-button>
          <el-button @click="cancel()">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="Section">
import { listOrder, getRefund, putccanel, getdefuis, enableGoods } from '@/api/operates/section/index';
import { StuinsQuery, CuionseVO, TonscuCine } from '@/api/operates/section/types';
// 获取toke的方法
import { globalHeaders } from "@/utils/request";
import useUserStore from '@/store/modules/user';
const permissions = useUserStore().permissions;
const router = useRouter();
const huonseom = reactive<UploadOption>({
  headers: globalHeaders(),
  url: import.meta.env.VITE_APP_BASE_API + '/file/upload'
})
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const columns = ref<FieldOption[]>([
  { key: 0, label: `ID`, visible: true, children: [] },
  { key: 1, label: `昵称`, visible: true, children: [] },
  { key: 2, label: `头像`, visible: true, children: [] },
  { key: 3, label: `分成比例`, visible: true, children: [] },
  { key: 4, label: `近30日gmv`, visible: true, children: [] },
  { key: 5, label: `直播场次`, visible: true, children: [] },
  { key: 6, label: `商品总数`, visible: true, children: [] },
  { key: 7, label: `类目简介`, visible: true, children: [] },
  { key: 8, label: `切片要求`, visible: true, children: [] },
  { key: 9, label: `切片须知`, visible: true, children: [] },
  { key: 10, label: `创建时间`, visible: true, children: [] },
  { key: 11, label: `申请人数`, visible: true, children: [] },
  { key: 12, label: `处理中人数`, visible: true, children: [] },
  { key: 13, label: `已处理人数`, visible: true, children: [] },
  { key: 14, label: `已拒绝人数	`, visible: true, children: [] },
  { key: 15, label: `上架状态`, visible: true, children: [] },
])

const initFormData: TonscuCine = {
  id: undefined,
  nickname: '',
  avatar: '',
  rate: '',
  orderAmount: '',
  liveCount: '',
  goodsNum: '',
  intro: '',
  demand: '',
  guide: '',
}
const data = reactive<PageData<TonscuCine, StuinsQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    enable: '',
  },
  rules: {
    nickname: [{ required: true, message: "昵称不能为空", trigger: "blur" }],
    rate: [{ required: true, message: "分成比例不能为空", trigger: "blur" }],
    orderAmount: [{ required: true, message: "近30日GMV不能为空", trigger: "blur" }],
    liveCount: [{ required: true, message: "直播场次不能为空", trigger: "blur" }],
    goodsNum: [{ required: true, message: "商品总数不能为空", trigger: "blur" }],
    intro: [{ required: true, message: "类目简介不能为空", trigger: "blur" }],
    demand: [{ required: true, message: "切片要求不能为空", trigger: "blur" }],
    guide: [{ required: true, message: "切片须知不能为空", trigger: "blur" }],
  },
})
const { queryParams, form, rules } = toRefs(data)

const suinoeu = reactive<DialogOption>({
  visible: false,
  title: ''
});
const ordersListl = ref<CuionseVO[]>([]);
const total = ref(0);
const loading = ref(true)
const showSearch = ref(true)
const enableFlag = ref(false)
const queryFormRef = ref<ElFormInstance>();
const configFormRef = ref<ElFormInstance>();

/**
 * 查询的是否违规
 */
const options = [
  {
    value: 1,
    label: '上架',
  },
  {
    value: 0,
    label: '下架',
  }
]

/**
 * 查询切片达人列表
 */
const getList = async () => {
  loading.value = true;
  const res = await listOrder(queryParams.value);
  ordersListl.value = res.data.list;
  total.value = res.data.total;
  loading.value = false;
}

/**
 * 素材审核{启用/禁用}
 */
const approve = async (row: CuionseVO) => {
  try {
    let text = row.enable === 1 ? "上架" : "下架";
    await proxy?.$modal.confirm(`是否确认${text}达人切片`);
    await enableGoods(row.id as string | number);
    getList();
    proxy?.$modal.msgSuccess(text + "成功");
  } catch (error) {
    row.enable = row.enable === 1 ? 0 : 1;
  }
}

/**
 * 搜索按钮操作
 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/**
 * 重置按钮操作
 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}


/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  suinoeu.visible = true;
  suinoeu.title = "新增达人切片";
}

/** 新增和修改的弹窗表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  configFormRef.value?.resetFields();
}

/** 弹窗确认按钮 */
const submitForm = () => {
  configFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      form.value.id ? await putccanel(form.value) : await getRefund(form.value);
      proxy?.$modal.msgSuccess("操作成功");
      suinoeu.visible = false;
      await getList();
    }
  });
}
/** 弹窗取消按钮 */
const cancel = () => {
  reset();
  suinoeu.visible = false;
}

// 添加弹窗的图片上传
const handleAvatarSuccess = (res: any) => {
  // console.log(res);
  // 如果上传成功
  if (res.code === 200) {
    form.value.avatar = res.data.url.replace('juguanghe.oss-cn-hangzhou.aliyuncs.com', 'oss.fengjuhe.com');
  } else {
    proxy?.$modal.loading(res.msg);
  }
}

/**
 * 达人切片详情
 */
const handleDetails = (row: CuionseVO) => {
  router.push({ path: `/section/detail/${row.id}` });
}

/** 修改按钮操作 */
const handleUpdate = async (row: CuionseVO) => {
  reset();
  const configId = row.id;
  const res = await getdefuis(configId as string | number);
  Object.assign(form.value, res.data);
  suinoeu.visible = true;
  suinoeu.title = "修改参数";
}

// 达人切片审核按钮的判断
const enableFn = () => {
  if (permissions[0] !== '*:*:*') {
    enableFlag.value = !permissions.includes('gms:section:updown')
  }
}

onMounted(() => {
  getList();
  enableFn();
});
</script>

<style scoped>
.avatar {
  width: 150px;
  height: 150px;
  display: block;
  object-fit: contain;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  text-align: center;
}
</style>